package cn.gbase.jiangsu.data.transfer.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierInfo;
import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.bean.SystemLog;
import cn.gbase.jiangsu.data.transfer.bean.SystemUser;
import cn.gbase.jiangsu.data.transfer.service.SupplierService;
import cn.gbase.jiangsu.data.transfer.service.SupplierUserService;
import cn.gbase.jiangsu.data.transfer.service.SystemLogService;
import cn.gbase.jiangsu.data.transfer.util.DefaultPasswordEncoder;

import com.google.common.collect.Lists;

@IocBean(args = { "refer:dao" })
@At("/supplierAdmin")
@Filters(@By(type = CheckSession.class, args = { "supplierUser", "jsp:/supplierIndex" }))
public class SupplierAdminAction extends IdEntityService<SupplierUser> {

	@Inject
	private SupplierUserService supplierUserService;

	@Inject
	private SupplierService supplierService;

	@Inject("java:$config.get('supplierUserAclStr')")
	private String supplierUserAclStr;

	@Inject
	private SystemLogService systemLogService;

	public SupplierAdminAction() {
		super();
	}

	public SupplierAdminAction(Dao dao) {
		super(dao);
	}

	@At("/toEditInfo")
	@Ok("jsp:/supplier/supplierEditInfo")
	public void toEditInfo(HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		SupplierInfo supplierInfo = this.dao().fetch(SupplierInfo.class,
				Cnd.where("supplierId", "=", u.getSupplierId()));
		request.setAttribute("formdata", supplierInfo);
		UUID uuid = UUID.randomUUID();
		if (supplierInfo == null)

			request.setAttribute("idNew", uuid);
		else
			request.setAttribute("idNew", supplierInfo.getId());
	}

	/**
	 * 保存信息.
	 * 
	 * @param sp
	 */
	@At("/editInfo")
	@Ok("jsp:/supplier/supplierEditInfo")
	public void saveProduct(@Param("..") SupplierInfo info, @Param("idNew") String idNew, HttpSession session,
			HttpServletRequest request) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");

		SupplierInfo si = (SupplierInfo) supplierService.updateOrSaveInfo(info, u, idNew);
		request.setAttribute("idNew", si.getId());
		request.setAttribute("formdata", si);

	}

	/**
	 * 用户登录.
	 * 
	 * @param user
	 *            用户数据
	 * @param request
	 * @param session
	 */
	@At("/login")
	@POST
	@Ok(">>:/supplierMain")
	@Fail("jsp:/supplierIndex")
	@Filters
	public void login(@Param("..") SystemUser user, HttpServletRequest request, HttpSession session) {

		//回传数据
		request.setAttribute("formdata", user);

		// 取得用户
		SupplierUser u = this.dao().fetch(SupplierUser.class,
				Cnd.where("username", "=", user.getUsername()).and("status", "=", 1));
		// 用户不存在
		if (u == null) {
			request.setAttribute("msg", "用户名不存在");
			throw new RuntimeException();
		}
		Supplier supplier = this.dao().fetch(Supplier.class, u.getSupplierId());

		// 密码错误
		String encodePass = new DefaultPasswordEncoder("MD5").encode(user.getPw());
		if (!u.getPw().equals(encodePass)) {
			request.setAttribute("msg", "密码错误！");
			throw new RuntimeException();
		}

		// 保存到session
		session.setAttribute("supplierUser", u);
		session.setAttribute("supplier", supplier);

		// 权限名称，初始权限

		String[] aclNameArray = supplierUserAclStr.split(",");
		char[] aclArray = u.getAclStr().toCharArray();
		String[] aclList = new String[aclArray.length];
		for (int i = 0; i < aclArray.length; i++) {
			aclList[i] = String.valueOf(aclArray[i]);
		}
		// 权限
		session.setAttribute("supplierAclNameArray", aclNameArray);
		session.setAttribute("supplierAclArray", aclList);

		SystemLog logger = new SystemLog();
		logger.setOperatorId(u.getId());
		logger.setOperType(1);
		//4是供货商平台
		logger.setOperModular(4);
		logger.setOperContent("供货商用户" + u.getUsername() + "登录供货商平台");
		systemLogService.addSystemLog(logger);
	}

	@At("/logout")
	@Ok("jsp:/supplierIndex")
	@Filters
	public void logout(HttpServletRequest request, HttpSession session) {
		SupplierUser u = (SupplierUser) session.getAttribute("supplierUser");
		if (u != null) {
			SystemLog logger = new SystemLog();
			logger.setOperatorId(u.getId());
			logger.setOperType(1);
			//4是供货商平台
			logger.setOperModular(4);
			logger.setOperContent("供货商用户" + u.getUsername() + "退出供货商平台");
			systemLogService.addSystemLog(logger);
			session.removeAttribute("supplierUser");
		}
	}

	/**
	 * 跳转到修改密码页面.
	 */
	@At("/toUpdatePW")
	@Ok("jsp:/supplier/updatePW")
	public void toUpdatePage() {
	}

	/**
	 * 修改密码.
	 * @param user 用户信息
	 * @param request
	 * @param session
	 */
	@At("/updatePW")
	@POST
	@Ok(">>:/supplierAdmin/ok")
	@Fail("jsp:/supplier/updatePW")
	public void add(@Param("..") SupplierUser user, HttpServletRequest request, HttpSession session) {

		// 取得用户
		SupplierUser loginUser = (SupplierUser) session.getAttribute("supplierUser");

		//输入密码加密
		String encodePass = new DefaultPasswordEncoder("MD5").encode(user.getPw());

		//比较
		if (!encodePass.equals(loginUser.getPw())) {
			request.setAttribute("msg", "密码输入错误");
			throw new RuntimeException();
		}
		user.setId(loginUser.getId());
		supplierUserService.updatePWS(user);
		SystemLog logger = new SystemLog();
		logger.setOperatorId(loginUser.getId());
		logger.setOperType(1);
		//4是供货商平台
		logger.setOperModular(4);
		logger.setOperContent("供货商用户" + loginUser.getUsername() + "修改密码");
		systemLogService.addSystemLog(logger);
	}

	@At("/ok")
	@Ok("jsp:/supplier/ok")
	public void toOkPage(HttpServletRequest request) {
	}

	@At("/listUser")
	@Ok("jsp:/supplier/listSupplierUser")
	public QueryResult list(@Param("sid") int sid, @Param("p") int pageNumber, @Param("username") String username,
			@Param("realname") String realname, HttpServletRequest request, HttpSession session) {
		// 取得用户
		SupplierUser loginUser = (SupplierUser) session.getAttribute("supplierUser");

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("username", username);
		itemMap.put("realname", realname);
		itemMap.put("sid", "" + sid);
		request.setAttribute("formdata", itemMap);

		// 查询数据
		QueryResult list = supplierUserService.getUserList(pageNumber, username, realname, sid, loginUser.getId());
		List<SupplierUser> userlist = (List<SupplierUser>) list.getList();
		for (SupplierUser user : userlist) {
			if (loginUser.getId() == user.getId()) {
				userlist.remove(user);
				break;
			}
		}
		list.setList(userlist);
		return list;
	}

	@At("/toAddUser")
	@Ok("jsp:/supplier/editSupplierUser")
	public void toAddPage(@Param("sid") int sid, HttpServletRequest request, HttpSession session) {

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("supplierId", "" + sid); // 供货商ID
		request.setAttribute("formdata", itemMap);
		//所有权限
		String[] aclNameArray = supplierUserAclStr.split(",");
		List<String> aclNameArrayUser = Lists.newArrayList();
		//登录人的所有权限
		String[] aclList = (String[]) session.getAttribute("supplierAclArray");
		for (int i = 0; i < aclList.length; i++) {
			if ("1".equals(aclList[i]))
				aclNameArrayUser.add(aclNameArray[i]);
		}
		//编辑用户的权限
		String[] aclListUser = new String[aclList.length];
		// 权限
		request.setAttribute("supplierAclNameArrayUser", aclNameArrayUser);
		request.setAttribute("supplierAclArrayUser", aclListUser);

	}

	@At("/addUser")
	@POST
	@Ok(">>:/supplierAdmin/listUser?p=1&sid=${obj.supplierId}")
	@Fail("jsp:/supplier/editSupplierUser")
	public SupplierUser addUser(@Param("..") SupplierUser user, HttpServletRequest request, HttpSession session) {
		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("supplierId", "" + user.getSupplierId()); // 供货商ID
		request.setAttribute("formdata", itemMap);
		//所有权限
		String[] aclNameArray = supplierUserAclStr.split(",");
		List<String> aclNameArrayUser = Lists.newArrayList();
		//登录人的所有权限
		String[] aclList = (String[]) session.getAttribute("supplierAclArray");
		for (int i = 0; i < aclList.length; i++) {
			if ("1".equals(aclList[i]))
				aclNameArrayUser.add(aclNameArray[i]);
		}
		//编辑用户的权限
		String[] aclListUser = new String[aclList.length];
		// 权限
		request.setAttribute("supplierAclNameArrayUser", aclNameArrayUser);
		request.setAttribute("supplierAclArrayUser", aclListUser);
		// 取得用户
		SupplierUser loginUser = (SupplierUser) session.getAttribute("supplierUser");

		if (!supplierService.addOrUpdUser(user)) {
			request.setAttribute("errmsg", "该用户名的用户已经存在。"); // 错误信息
			request.setAttribute("formdata", user); // 表单数据
			throw new RuntimeException();
		}
		SystemLog logger = new SystemLog();
		logger.setOperatorId(loginUser.getId());
		logger.setOperType(1);
		//4是供货商平台
		logger.setOperModular(4);
		logger.setOperContent("供货商用户" + loginUser.getUsername() + "维护用户信息：" + user.getUsername());
		systemLogService.addSystemLog(logger);
		return user;
	}

	@At("/toEditUser")
	@Ok("jsp:/supplier/editSupplierUser")
	public void toEditPage(@Param("id") int userId, HttpServletRequest request, HttpSession session) {

		// 取得用户数据，放入表单中
		SupplierUser user = supplierService.getUser(userId);
		request.setAttribute("formdata", user);
		//所有权限
		String[] aclNameArray = supplierUserAclStr.split(",");
		List<String> aclNameArrayUser = Lists.newArrayList();
		//登录人的所有权限
		String[] aclList = (String[]) session.getAttribute("supplierAclArray");
		for (int i = 0; i < aclList.length; i++) {
			if ("1".equals(aclList[i]))
				aclNameArrayUser.add(aclNameArray[i]);
		}
		//编辑用户的权限
		char[] aclArray = user.getAclStr().toCharArray();
		String[] aclListUser = new String[aclArray.length];
		for (int i = 0; i < aclArray.length; i++) {
			aclListUser[i] = String.valueOf(aclArray[i]);
		}
		// 权限
		request.setAttribute("supplierAclNameArrayUser", aclNameArrayUser);
		request.setAttribute("supplierAclArrayUser", aclListUser);
	}

	/**
	 * 删除用户.
	 */
	@At("/deleteUser")
	@Ok("json")
	public String deleteUser(@Param("id") int id, HttpSession session) {
		// 取得用户
		SupplierUser loginUser = (SupplierUser) session.getAttribute("supplierUser");
		supplierService.deleteUser(id);
		SystemLog logger = new SystemLog();
		logger.setOperatorId(loginUser.getId());
		logger.setOperType(1);
		//4是供货商平台
		logger.setOperModular(4);
		logger.setOperContent("供货商用户" + loginUser.getUsername() + "删除id为" + id + "的用户");
		systemLogService.addSystemLog(logger);
		return "{id:0}";
	}

	/**
	 * 删除多个用户.
	 */
	@At("/deleteManyUser")
	@Ok("json")
	public String deleteManyUser(@Param("idStr") String idStr, HttpSession session) {
		// 取得用户
		SupplierUser loginUser = (SupplierUser) session.getAttribute("supplierUser");
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			supplierService.deleteUser(Integer.valueOf(id));
			SystemLog logger = new SystemLog();
			logger.setOperatorId(loginUser.getId());
			logger.setOperType(1);
			//4是供货商平台
			logger.setOperModular(4);
			logger.setOperContent("供货商用户" + loginUser.getUsername() + "删除id为" + id + "的用户");
			systemLogService.addSystemLog(logger);
		}
		return "{id:0}";
	}

	/**
	 * 跳转到供货商首页.
	 */
	@At("/main")
	@Ok("jsp:/supplierMain")
	public void toMainPage() {
	}

}
